import 'package:sqflite/sqflite.dart';


///表数据操作接口
abstract class JDTableAction {
  void saveData(DataModel model);

  void deleteData(int id);

  void update(DataModel model);

  Future<int> getDataCount();

  Future<List<DataModel>> getAllData();
}

///INote的的具体实现
class BaseTableAction implements JDTableAction {
  Database db;
  String tableName;
  String sqlString;

  BaseTableAction(
      {required this.db, required this.tableName, required this.sqlString}) {
    // name TEXT, value INTEGER, num REAL;
    // 需要查询的属性 可以单独写成属性
    db.execute(sqlString);
  }

  @override
  Future<List<DataModel>> getAllData() async {
    var results = await db.rawQuery('select * from $tableName');
    var list = results.map((item) => DataModel.fromJson(item)).toList();
    return list;
  }

  @override
  void saveData(DataModel model) {
    db.insert(tableName, model.toJson()).then((value) {
      print('insert ----${value == 0 ? 'insert失败' : 'insert成功'}');
    });
  }

  @override
  void deleteData(int id) {
    db.delete(tableName, where: 'id=$id');
  }

  @override
  Future<int> getDataCount() async {
    var result = await db.query(tableName, columns: ['COUNT(*) as cnt']);
    return result.first['cnt'] as int;
  }

  @override
  void update(DataModel model) {
    db.update(tableName, model.toJson(),
        where: 'id =?', whereArgs: [model.id]).then((value) {
      print('update ----${value == 0 ? '更新失败' : '更新成功'}');
    });
  }
}


class DataModel {
  int? id;
  // 可以存 jsonString,使用时候 转成model
  String? content;

  DataModel({this.id, this.content});

  ///提供fromJson以方便将数据库查询结果，转成Dart Model
  DataModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    content = json['content'];
  }

  ///提供toJson以方便在持久化数据的时候使用
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['content'] = content;
    return data;
  }
}